package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.SetmealDto;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CheckGroupService;
import com.itheima.service.CheckItemService;
import com.itheima.service.SetmealGroupService;
import com.itheima.service.SetmealService;
import com.itheima.support.PageResult;
import com.itheima.support.QueryPageBean;
import com.itheima.utils.FileUtil;
import com.itheima.utils.RedisUtil;
import com.itheima.vo.SetmealVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Set;

@DubboService
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Resource
    private SetmealGroupService setmealGroupService;

    @Resource
    private CheckGroupService checkGroupService;

    @Resource
    private CheckItemService checkItemService;


   /* @Resource
    private RedisTemplate<String,Object> redisTemplate;*/

    @Override
    @Transactional
    public boolean saveSetmeal(SetmealVO setmealVO) {
        //保存setmeal
        this.saveOrUpdate(setmealVO);

        //套餐新增/编辑维护redis
        if (ObjectUtils.isEmpty(setmealVO.getImg())==false){
            //最新的文件移除垃圾箱 temp-rubbish
           // redisTemplate.opsForSet().remove("temp-rubbish",setmealVO.getImg());
            RedisUtil.removeOfSet("temp-rubbish",setmealVO.getImg());
        }
        //删除中间表
        setmealGroupService.deleteById(setmealVO.getId());
        //添加中间表
        setmealGroupService.saveSetmealGroup(setmealVO.getId(),setmealVO.getGroups());
        return true;
    }

    //分页查询
    @Override
    public PageResult findByPage(QueryPageBean pageBean) {
        //模糊查询
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        if(ObjectUtils.isEmpty(pageBean.getQueryString()) == false){
            queryWrapper.like("code",pageBean.getQueryString()).or()
                    .like("name",pageBean.getQueryString()).or()
                    .like("help_code",pageBean.getQueryString());
        }
        IPage<Setmeal>page=this.page(new Page<>(pageBean.getCurrentPage(),pageBean.getPageSize()), queryWrapper);

        return new PageResult(page.getTotal(),page.getRecords());
    }

    /**
     * 清理垃圾的接口实现
     * */
    @Override
    public void clearOssPic() {
        /*
        * Function<T,R>接口:表示转换接口，用来将前置类型T转换为后置类型R,
        * 我们只想要它里面的的key值
        * */

        /*Set<String> rubbishSet = redis
        Template.opsForSet().members("temp-rubbish").stream()
                .map(fileKeyObj->(String)fileKeyObj).collect(Collectors.toSet());*/
        Set<String> rubbishSet = RedisUtil.members("temp-rubbish");
        /*.map(fileKeyObj -> (String) fileKeyObj).collect(Collectors.toSet());*/
        if (rubbishSet!=null&&rubbishSet.isEmpty()==false){
            //遍历Set集合的目的就是要里面的key值
            rubbishSet.forEach(fileKey->{
                //判断辅助key是否存在
                //String类型的 判断key是否存在：redisTemplate.hasKey(String key)
                //if (redisTemplate.hasKey("file:"+fileKey)==false){
                if (RedisUtil.hasKey("file:"+fileKey)==false){

                    //删除Oss文件
                    FileUtil.delete(fileKey);
                    //如果临时辅助key都消失了还不删除零售垃圾桶的的key？
                    //redisTemplate.opsForSet().remove("temp-rubbish",fileKey);
                    RedisUtil.removeOfSet("temp-rubbish",fileKey);
                }
            });
        }

    }

    @Override
    public SetmealDto detail(Long setmealId) {
        //先查询redis缓存中是否存在
        SetmealDto setmealDetailValue = RedisUtil.get("setmealDetail");
        if (setmealDetailValue==null){
            //先拿套餐的基本信息
            Setmeal setmeal=this.getById(setmealId);
            if (setmeal==null){
                return null;
            }
            //创建套餐DTO
            SetmealDto setmealDto = new SetmealDto();
            //对象setmeal的信息一样的全部封装到DTO中
            BeanUtils.copyProperties(setmeal,setmealDto);
            //通过套餐查询检查组
            setmealDto.setCheckGroups(checkGroupService.selectBySetmealId(setmealId));
            //维护检查组所对应的检查列表
            if (setmealDto.getCheckGroups()!=null){
                //消费函数式接口
                setmealDto.getCheckGroups().stream().forEach(checkGroupDto -> {
                    checkGroupDto.setCheckItems(checkItemService.findByGroupId(checkGroupDto.getId()));
                });
            }
            RedisUtil.set("setmealDetail",setmealDto);
        }



        return RedisUtil.get("setmealDetail");

    }
}